<template>
        <span class="dialog-footer">
          <div class="filter-container">
 <el-descriptions
     :column="3"
     :size="size"
     v-model="appState.orderData"
     border
 >
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          订单号
        </div>
      </template>
      {{appState.orderData.id}}
    </el-descriptions-item>
       <el-descriptions-item>
      <template #label>
        <div class="cell-item">
         客户名
        </div>
      </template>
       {{appState.orderData.customer.name}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
         客户电话
        </div>
      </template>
       {{appState.orderData.customer.phone}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          司机
        </div>
      </template>
      <template v-for="driver in appState.orderData.drivers" :key="driver.id">
        {{ driver.driverName+" tel:  "+driver.driverPhone}}<br>
  </template>
    </el-descriptions-item>
      <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          路线
        </div>
      </template>
        {{appState.orderData.line.startAddress+" 》》》》 "+appState.orderData.line.endAddress}}

    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          订单金额(元)
        </div>
      </template>
      {{appState.orderData.amount}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          订单状态
        </div>
      </template>
      {{appState.orderData.orderStatus}}
    </el-descriptions-item>
       <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          订单创建时间
        </div>
      </template>
      {{appState.orderData.createTime}}
    </el-descriptions-item>
          <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          订单发货时间
        </div>
      </template>
      {{appState.orderData.sendTime}}
    </el-descriptions-item>
  </el-descriptions>
    <el-table :data="appState.orderData.goodsList"  style="width: 100%" >
      <el-table-column label="序号"  align="center"><template v-slot ="scope">{{ scope.$index + 1 }}</template></el-table-column>
       <el-table-column label="货物编号"  align="center" prop="id"></el-table-column>
       <el-table-column label="订单号" align="center" prop="order_id" ></el-table-column>
      <el-table-column label="仓库名" align="center" prop="depository.name" ></el-table-column>
      <el-table-column label="司机名" align="center" prop="driver.driverName" ></el-table-column>
      <el-table-column label="包装类型" align="center" prop="pack.type" ></el-table-column>
      <el-table-column label="货物名" align="center" prop="name" ></el-table-column>
      <el-table-column label="货物类型" align="center" prop="type"></el-table-column>
      <el-table-column label="重量(千克)" align="center" prop="weight"></el-table-column>
      <el-table-column label="体积(立方米)" align="center" prop="size"></el-table-column>
      <el-table-column label="数量(件)" align="center" prop="quantity" ></el-table-column>
      <el-table-column label="货物性质" align="center" prop="nature" ></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template v-slot="{row}">
                  <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                </template>
      </el-table-column>
    </el-table>

          </div>

          <el-button type="primary"  @click="handleCreate" >添加</el-button>
        </span>
<!--    </template>-->
<!--  </el-dialog>-->












  <!--  新增货物弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible"
      title="新增货物"
      width="30%"
  >
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
            <el-form v-model="driverData">
    <el-row>

        <el-col span="3">
        <el-form-item label="货物名称">
          <el-input  placeholder="请输入货物名称" v-model="driverData.name"  clearable />
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item label="货物类型">
          <el-input  placeholder="请输入货物类型" v-model="driverData.type"  clearable />
        </el-form-item>
      </el-col>

      <el-col span="3">
        <el-form-item label="重量(千克)">
          <el-input  placeholder="请输入货物重量" v-model="driverData.weight" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="体积(立方米)">
          <el-input  placeholder="请输入货物体积" v-model="driverData.size"  clearable/>
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item label="数量(件)">
          <el-input  placeholder="请输入货物数量" v-model="driverData.quantity" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="货物性质">
          <el-input  placeholder="请输入货物性质" v-model="driverData.nature"  clearable />
        </el-form-item>
      </el-col>
       <el-form-item label="选择仓库">
    <select v-model="driverData.depository" placeholder="请选择仓库" style="width: 240px">
      <option
          v-for="item in state.options2"
          :key="item"
          :label="item.name"
          :value="item"
      />
    </select>
     </el-form-item>
      <el-form-item label="选择司机">
<select v-model="driverData.driver" placeholder="请选择司机" style="width: 240px" clearable>
             <option
            v-for="item in state.options3"
            :key="item"
            :label="item.driverName"
            :value="item"
        >
        </option>
</select>
        <!--      <option-->
        <!--          v-for="item in state.options3"-->
        <!--          :key="item"-->
        <!--          :label="item.driverName"-->
        <!--          :value="item"-->
        <!--      >-->
        <!--      </option>-->
        </el-form-item>
        <el-form-item label="选择包装">
    <select v-model="driverData.pack" placeholder="请选择包装" style="width: 240px" >
      <option
          v-for="item in state.options4"
          :key="item"
          :label="item.type"
          :value="item"
      />
    </select>
     </el-form-item>
    </el-row>
              </el-form>
  </div>

          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleAdd" >
            确定
          </el-button>
        </span>
    </template>
  </el-dialog>



</template>

<script setup>
import {inject, reactive, ref, computed, watch, watchEffect,defineProps} from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import instance from "../../../../request";
const state=reactive({
  dataList: [],//表格数据
  options1:[],
  options2:[],
  options3:[],
  options4:[],
  selectedOptions: [],
  rowId:null,
  formData: {},
  goodsData: {},
  dialogFormVisible: false,//添加表单是否可见
  dialogFormVisible4Edit:false,//编辑表单是否可见
})
const appState=inject('appState');
state.dataList=appState.orderData.goodsList
//获取所有订单id
const getOrderId=()=>{
  instance.get('/goods/oid').then(res=>{
    // console.log(res.data)
    state.options1=res.data
  })
}

//获取所有仓库
const getDepository=()=>{
  instance.get('/goods/depository').then(res=>{
    for (let i = 0; i < res.data.length; i++) {
      console.log(appState.orderData.line.startAddress)
      if (res.data[i].address===appState.orderData.line.startAddress){
        state.options2.push(res.data[i])
      }
    }

    console.log(state.options2)
    console.log(availableWarehouses)
    // console.log(res.data)
  })
}
//获取所有司机
const getDriver=()=>{

}
let driverData=reactive({
  name:'',
  type:'',
  weight:'',
  size:'',
  quantity:'',
  nature:'',
  depository:{},
  driver:{
    driverName:'无司机可派'
  },
  pack:{}
})
// 使用ref创建响应式数据
let totalSize = reactive({value:0});
let totalWeight =reactive({value:0});
// 使用watch监听inputValue的变化
let goodsAllSize=0.0
let goodsAllWeight=0.0
watchEffect(async () => {
  const goods = driverData; // Consider renaming if necessary

  if (hasValidInput(goods)) {
    goodsAllWeight = goods.weight * goods.quantity;
    goodsAllSize = goods.size * goods.quantity;

    instance.post('/order/driver/', appState.orderData).then(async res => {
      let driver = []
      console.log(appState.orderData.goodsList)
      if (appState.orderData.goodsList !== null&&appState.orderData.goodsList!==[]&&appState.orderData.goodsList.length!==0) {
        for (let i = 0; i < res.data.length; i++) {
          let res1 =await  instance.get("/order/totalWeight/" + res.data[i].id)
          totalWeight.value=res1.data
          let res2 = await instance.get("/order/totalSize/" + res.data[i].id)
          totalSize.value=res2.data
          console.log(totalWeight.value,"OUT")
          if (res.data[i].size>=totalSize.value+goodsAllSize&&res.data[i].carLoad>=totalWeight.value+goodsAllWeight&&res.data[i].status===1){
            console.log(res.data[i])
            driver.push(res.data[i])
          }
        }
        if (driver.length===0){
          for (let i = 0; i < res.data.length; i++) {
            console.log(res.data[i].size>=goodsAllSize)
            if (res.data[i].size>=goodsAllSize&&res.data[i].carLoad>=goodsAllWeight&&res.data[i].status===0){
              console.log(res.data[i])
              driver.push(res.data[i])
            }
          }
        }
      } else {
        for (let i = 0; i < res.data.length; i++) {
          console.log(res.data[i].size>=goodsAllSize)
          if (res.data[i].size>=goodsAllSize&&res.data[i].carLoad>=goodsAllWeight&&res.data[i].status===0){
            console.log(res.data[i])
            driver.push(res.data[i])
          }
        }
      }
      console.log(driver);
      if (driver.length===0) {
        alert("暂无司机在本地，请添加司机，以保证订单正常运行");
      } else {
        state.options3=driver
      }
      if (driverData.driver.length===0) {
        alert("暂无司机在本地，请添加司机，以保证订单正常运行");
      }
      console.log(state.options3);
    });
  }
});

function hasValidInput(goods) {
  return (
      goods.weight !== null &&
      goods.size !== null &&
      goods.quantity !== null &&
      goods.weight !== '' &&
      goods.size !== '' &&
      goods.quantity !== '' &&
      goods.weight !== undefined &&
      goods.size !== undefined &&
      goods.quantity !== undefined
  );
}

//获取所有包装
const getPackage=()=>{
  instance.get('/goods/package').then(res=>{
    // console.log(res.data)
    state.options4=res.data
  })
}



const   handleCreate=(row)=> {
  if (appState.orderData.orderStatus===4){
    ElMessage({
      type: 'warning',
      message: '订单已结束，无法添加货物',
    })
  }else {
    getOrderId();
    getDepository();
    getPackage();
    state.dialogFormVisible = true;
    resetForm();
  }
}

const resetForm=()=> {
  driverData.name=''
     driverData. type=''
      driverData.weight=''
     driverData. size=''
      driverData.quantity=''
      driverData.nature=''
      driverData.depository={}
  driverData.driver={}
  driverData.pack={}
  state.formData={};
}
const cancel=()=>{
  state.dialogFormVisible = false;
  state.dialogFormVisible4Edit = false;
  state.options2=[]
  state.options3=[]
  resetForm()
  // this.$message.info("操作取消");
}

//添加

const handleAdd=()=> {
  driverData.order_id=appState.orderData.id
  console.log(driverData)
  instance.post("/order/goods/",driverData).then((res)=>{
//如果操作成功，关闭弹层，显示数据
    if(res.flag){
      state.dialogFormVisible = false;
      console.log("添加成功")
      instance.get("/order/"+driverData.order_id).then(res=>{
        if(res.flag){
//展示弹层，加载数据
          appState.orderData=res.data
          state.dialogFormVisibleAddGoods=true;
        }else{
          console.log("失败")
        }
      })
    }else {
      console.log("添加失败")
    }
  }).finally(()=>{
    state.options2=[];
  })
}

const handleDelete=(row)=> {
  if (appState.orderData.orderStatus === 4) {
    ElMessage({
      type: 'warning',
      message: '订单已结束，无法删除货物',
    })
  } else {
    instance.get("/goods/getOrderStatus/" + row.order_id).then(res => {
      console.log(res.data)
      if (res.data) {
        ElMessageBox.confirm(
            '是否删除该货物?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              instance.delete("/goods/" + row.id).then((res) => {
                if (res.flag) {
                  state.dialogFormVisible = false;
                  instance.get("/order/" + appState.orderData.id).then(resp => {
                    appState.orderData = resp.data
                  })
                  ElMessage({
                    type: 'success',
                    message: '删除成功',
                  })
                } else {
                  ElMessage({
                    type: 'error',
                    message: '删除失败',
                  })
                }
              })
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '已取消删除',
              })
            })
      } else {
        ElMessage({
          type: 'error',
          message: '货物已在运输中,禁止删除',
        })
      }
    })

  }
}
const availableWarehouses = computed(() => {
  const totalVolume = state.formData.size * state.formData.quantity;

  return state.options2.filter(warehouse => {
    let warehouseCapacity=0;
    if (warehouse.type==="小型仓库"){
      warehouseCapacity = 1000;
    }else if (warehouse.type==="中型仓库"){
       warehouseCapacity = 3000;
    }else if (warehouse.type==="大型仓库"){
      warehouseCapacity = 5000;
    }

    const existingGoodsVolume = ()=>{
      instance.get("/goods/depository/"+warehouse.id).then((res)=>{
        return res.data.data
      })
    };

    if (totalVolume <= warehouseCapacity && totalVolume + existingGoodsVolume <= warehouseCapacity) {
      return true;
    } else {
      return false;
    }
    console.log(state.options2)
  });
});
</script>

<style scoped>

</style>